<?php

namespace App\Repository\Config;

use App\Model\Config\Config;
use App\Model\Config\ConfigData;
use App\Repository\IRepository;
use Hyperf\Contract\LengthAwarePaginatorInterface;
use Hyperf\Database\Model\Builder;

/**
 * 配置数据管理 Repository类
 */
class ConfigDataRepository extends IRepository
{
    public function __construct(
        protected readonly ConfigData $model,
    )
    {
    }

    /**
     * 搜索器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        if (isset($params['config_id']) && $params['config_id']) {
            $query->where('config_id', $params['config_id']);
        }
        if (isset($params['status']) && $params['status']){
            $query->where('status', $params['status']);
        }

        return $query;
    }


    public function handlePage(LengthAwarePaginatorInterface $paginator): array
    {
        $lists = $paginator->items();
        foreach ($lists as &$item) {
            foreach ($item['data'] as $data) {
                $value = $data['value'];
                if (in_array($data['type'], ['select', 'checkbox', 'radio'])) {
                    array_filter($data['options'], function ($option) use (&$value) {
                        if ($option['value'] == $value) {
                            $value = $option['label'];
                        }
                    });
                }
                $item[$data['identifier']] = $value;
            }
        }
        return [
            'total' => $paginator->total(),
            'per_page' => $paginator->perPage(),
            'current_page' => $paginator->currentPage(),
            'list' => $lists,
        ];
    }
}